<template>
  <div class="Account">
    <el-form label-width="60px" :model="from" :rules="rules" ref="fromRef" status-icon>
      <el-form-item label="账号" prop="name">
        <el-input v-model="from.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="from.password" type="password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'

import { ElMessage } from 'element-plus'

import { useLoginStore } from '@/store/login/login'
import { localCache } from '@/utils/cache'
import crypto from 'crypto-js'

import type { FormRules, FormInstance } from 'element-plus'
import type { IAccount } from '@/types/index'

const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const loginStore = useLoginStore()

const password = localCache.getCache(CACHE_PASSWORD) ?? ''
const decrypted = crypto.AES.decrypt(password, '584887097kk').toString(crypto.enc.Utf8)

const fromRef = ref<FormInstance>()
const from = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: decrypted
})

// 表单的规则校验
const rules: FormRules = {
  name: [
    { required: true, message: '请输入账号', trigger: 'blur' }
    // {
    //   message: '必须由20位以下数字或字母组成',
    //   trigger: 'blur',
    //   pattern: /^[a-z0-9]{1,20}$/
    // }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      min: 4,
      message: '密码长度至少为4位',
      trigger: 'blur'
    },
    {
      message: '密码必须包含大小写字母和数字的组合',
      trigger: 'blur',
      pattern: /^[a-z0-9A-Z]{4,}$/
    }
  ]
}

// 登录逻辑
function loginAction(isRememberPwd: boolean) {
  fromRef.value?.validate(async (valid) => {
    if (valid) {
      const name = from.name
      const password = from.password

      const encrypted = crypto.AES.encrypt(password, '584887097kk') // 密码加密

      loginStore.loginAccountAction({ name, password }).then((res) => {
        if (res.code === 0) {
          ElMessage({
            message: '登录成功',
            type: 'success'
          })
          if (isRememberPwd) {
            localCache.setCache(CACHE_NAME, name)
            localCache.setCache(CACHE_PASSWORD, encrypted.toString())
          } else {
            localCache.removeCache(CACHE_NAME)
            localCache.removeCache(CACHE_PASSWORD)
          }
        } else {
          ElMessage({
            message: '账户不存在',
            type: 'error'
          })
        }
      })
    } else {
      ElMessage({
        message: '请输入指定格式的账户或密码',
        type: 'warning'
      })
    }
  })
}

defineExpose({ loginAction })
</script>

<style lang="scss" scoped></style>
